package com.glory.wxelectricitypda.activity;


import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.wxelectricitypda.R;
import com.glory.wxelectricitypda.adapter.RDRequisitionAdapter;
import com.glory.wxelectricitypda.base.BaseDialogActivity;
import com.glory.wxelectricitypda.base.Constant;
import com.glory.wxelectricitypda.bean.RDRequisitionBean;
import com.glory.wxelectricitypda.bean.ResponseBean;
import com.glory.wxelectricitypda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_TextCallback;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

public class RDRequisitionActivity extends BaseDialogActivity {

    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.llmlotID)
    LinearLayout llmlotID;
    @BindView(R.id.llmEqpID)
    LinearLayout llmEqpID;
    @BindView(R.id.llmUseID)
    LinearLayout llmUseID;
    @BindView(R.id.useID)
    FreeUI_ClearEditText useID;
    @BindView(R.id.mlotID)
    FreeUI_ClearEditText mlotID;
    @BindView(R.id.eqpID)
    FreeUI_ClearEditText eqpID;
    @BindView(R.id.flXeuitdoc)
    FrameLayout flXeuitdoc;
    @BindView(R.id.tvXeuitdoc)
    TextView tvXeuitdoc;
    @BindView(R.id.ivXeuitdoc)
    ImageView ivXeuitdoc;
    @BindView(R.id.flEuitdoclines)
    FrameLayout flEuitdoclines;
    @BindView(R.id.tvEuitdoclines)
    TextView tvEuitdoclines;
    @BindView(R.id.ivEuitdoclines)
    ImageView ivEuitdoclines;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    private RDRequisitionAdapter adapter;

    private List<RDRequisitionBean.XEUITDOCLISTDTO> xeuitdoclist;
    private ArrayList<String> xeuitdocIDList = new ArrayList<>();
    private ArrayList<String> euitdoclinesList = new ArrayList<>();
    private Map<String, Long> xeuitdocMap = new HashMap<>();
    private Map<String, Long> euitdoclinesMap = new HashMap<>();
    private FreeUI_GeneralPop mXeuitdocPop;
    private FreeUI_GeneralPop mEuitdoclinesPop;
    private RDRequisitionBean.XEUITDOCLISTDTO.EUITDOCLINESDTO item1;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_rdrequisition;
    }

    @Override
    protected void initView() {

        freeUI_titleView.setTitle("研发领用");
        freeUI_titleView.setRightListener("发料", new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (llmUseID.getVisibility() == View.VISIBLE) {
                    // 按钮可见
                    if (useID.getText().toString().isEmpty()) {
                        showToast("请扫描工号！", false);
                        return;
                    }
                    if (eqpID.getText().toString().isEmpty()) {
                        showToast("请输入库房号！", false);
                        return;
                    }
                    Constant.CURRENT_USER = useID.getText().toString();
                } else {
                    // 按钮不可见
                    Constant.updateCurrentUser(getApplicationContext());
                }
                submit();
            }
        });

        recycler.setLayoutManager(new LinearLayoutManager(RDRequisitionActivity.this));
        recycler.setItemAnimator(new DefaultItemAnimator());
        recycler.addItemDecoration(new DividerItemDecoration(RDRequisitionActivity.this, 1));
        adapter = new RDRequisitionAdapter(null);
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        adapter.isFirstOnly(true);
        recycler.setAdapter(adapter);
    }

    @Override
    protected void initData() {

        queryXeuitdocList();

        initEdit(mlotID, s -> {

            if (s.contains("|")) {
                s = s.replace("|", ",").split(",")[2];
            }
            mlotID.setText(s);
            queryMlotID(s);
            mlotID.setText("");
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mlotID.requestFocus();
                }
            }, 500);
        });

        flXeuitdoc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                if (mXeuitdocPop != null) {
//                    if (mXeuitdocPop.isShowing()) {
//                        mXeuitdocPop.dismiss();
//                    }
//                } else {
                mXeuitdocPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flXeuitdoc.getWidth(), xeuitdocIDList, ivXeuitdoc, new FreeUI_TextCallback() {
                    @Override
                    public void onSuccess(String s) {
                        tvXeuitdoc.setText(s);
                        euitdoclinesList.clear();
                        euitdoclinesMap.clear();

                        for (RDRequisitionBean.XEUITDOCLISTDTO bean : xeuitdoclist) {
                            if (bean.getOBJECTRRN() == xeuitdocMap.get(s)) {
                                for (RDRequisitionBean.XEUITDOCLISTDTO.EUITDOCLINESDTO item : bean.getEUITDOCLINES()) {
                                    String ss = item.getMATERIALNAME() + " | " + item.getMATERIALDESC() + " | " + item.getUNITID() + " | " + item.getQTY();
                                    euitdoclinesList.add(ss);
                                    euitdoclinesMap.put(ss, item.getOBJECTRRN());
                                }
                            }
                        }

                    }
                });
//                }

                FreeApi_PopUtils.setArrowShow(ivXeuitdoc);
                mXeuitdocPop.showAsDropDown(flXeuitdoc, 0, 0);
            }
        });
        flEuitdoclines.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                mEuitdoclinesPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flEuitdoclines.getWidth(), euitdoclinesList, ivEuitdoclines, new FreeUI_TextCallback() {
                    @Override
                    public void onSuccess(String s) {
                        tvEuitdoclines.setText(s);

                        for (RDRequisitionBean.XEUITDOCLISTDTO bean : xeuitdoclist) {
                            if (bean.getOBJECTRRN() == xeuitdocMap.get(tvXeuitdoc.getText().toString())) {
                                for (RDRequisitionBean.XEUITDOCLISTDTO.EUITDOCLINESDTO item : bean.getEUITDOCLINES()) {
                                    if (item.getOBJECTRRN() == euitdoclinesMap.get(s)) {
                                        item1 = item;
                                    }
                                }
                            }
                        }
                        queryMlot();
                    }
                });

                FreeApi_PopUtils.setArrowShow(ivEuitdoclines);
                mEuitdoclinesPop.showAsDropDown(flEuitdoclines, 0, 0);
            }
        });

    }

    private void queryMlotID(String s) {

        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        JSONObject euItDocLine = new JSONObject();
        try {
            jsonObject1.put("ACTIONTYPE", "ACTIONRDOUTBYSCANCODEQUERY");
            jsonObject1.put("MLOTID",s);
            euItDocLine.put("OBJECTRRN", item1.getOBJECTRRN());
            euItDocLine.put("EUITDOCRRN", item1.getEUITDOCRRN());
            euItDocLine.put("DOCLINETYPE", item1.getDOCLINETYPE());
            euItDocLine.put("MATERIALNAME", item1.getMATERIALNAME());
            euItDocLine.put("MATERIALTYPE", item1.getMATERIALTYPE());
            euItDocLine.put("MATERIALDESC", item1.getMATERIALDESC());
            euItDocLine.put("UNITID", item1.getUNITID());
            euItDocLine.put("QTY", item1.getQTY());
            jsonObject1.put("EUITDOCLINE", euItDocLine);
            jsonObject.put("Data", jsonObject1);
            jsonObject.put("MessageName", "EUIT.MLOTAPPLYOUT");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<RDRequisitionBean>>(
                new TypeToken<ResponseBean<RDRequisitionBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<RDRequisitionBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    adapter.setNewData(response.body().getBody().getMATLIST());
                }
            }

            @Override
            public void onError(Response<ResponseBean<RDRequisitionBean>> response) {
                super.onError(response);
                loadError(response.getException(), "MLOTAPPLYOUT");
            }
        });

    }

    private void submit() {

        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        JSONObject euItDocLine = new JSONObject();
        String mm = "";
        if (adapter.getData().size()>0){
            mm = adapter.getData().get(0).getMLOTID();
        }
        try {
            jsonObject1.put("ACTIONTYPE", "ACTIONRDOUT");
            jsonObject1.put("MLOTID", mm);
            jsonObject1.put("EQPID", eqpID.getText().toString());
            euItDocLine.put("OBJECTRRN", item1.getOBJECTRRN());
            euItDocLine.put("EUITDOCRRN", item1.getEUITDOCRRN());
            euItDocLine.put("DOCLINETYPE", item1.getDOCLINETYPE());
            euItDocLine.put("MATERIALNAME", item1.getMATERIALNAME());
            euItDocLine.put("MATERIALTYPE", item1.getMATERIALTYPE());
            euItDocLine.put("MATERIALDESC", item1.getMATERIALDESC());
            euItDocLine.put("UNITID", item1.getUNITID());
            euItDocLine.put("QTY", item1.getQTY());
            jsonObject1.put("EUITDOCLINE", euItDocLine);
            jsonObject1.put("OUTLIST", new JSONArray(new Gson().toJson(adapter.getData())));
            jsonObject.put("Data", jsonObject1);
            jsonObject.put("MessageName", "EUIT.MLOTAPPLYOUT");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<RDRequisitionBean>>(
                new TypeToken<ResponseBean<RDRequisitionBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<RDRequisitionBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {

                    if (response.body().getBody().getSTORAGEID().isEmpty()) {
                        showToast("发料成功", true);
                        mlotID.setText("");
                        adapter.setNewData(null);
                        xeuitdocIDList.clear();
                        xeuitdoclist.clear();
                        xeuitdocMap.clear();
                        euitdoclinesList.clear();
                        euitdoclinesMap.clear();
                        tvEuitdoclines.setText("");
                        tvXeuitdoc.setText("");
                        eqpID.setText("");
                        llmlotID.setVisibility(View.GONE);

                        queryXeuitdocList();

                    } else {
                        FreeApi_DialogUtils.getConfirmDialog(RDRequisitionActivity.this, "确定", response.body().getBody().getSTORAGEID(), new FreeUI_CommonCallback() {
                            @Override
                            public void onSuccess() {

                                showToast("发料成功", true);
                                mlotID.setText("");
                                adapter.setNewData(null);
                                xeuitdocIDList.clear();
                                xeuitdoclist.clear();
                                xeuitdocMap.clear();
                                euitdoclinesList.clear();
                                euitdoclinesMap.clear();
                                tvEuitdoclines.setText("");
                                tvXeuitdoc.setText("");
                                eqpID.setText("");
                                llmlotID.setVisibility(View.GONE);

                                queryXeuitdocList();

                            }
                        }).show(getSupportFragmentManager(), "DIALOG");

                    }
                }
            }

            @Override
            public void onError(Response<ResponseBean<RDRequisitionBean>> response) {
                super.onError(response);
                loadError(response.getException(), "MLOTAPPLYOUT");
            }
        });
    }


    private void queryMlot() {

        llmlotID.setVisibility(View.GONE);
        llmEqpID.setVisibility(View.GONE);
        llmUseID.setVisibility(View.GONE);
        mlotID.setText("");
        eqpID.setText("");

        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        JSONObject euItDocLine = new JSONObject();
        try {
            jsonObject1.put("ACTIONTYPE", "ACTIONRDOUTBYEUITDOCQUERY");
            euItDocLine.put("OBJECTRRN", item1.getOBJECTRRN());
            euItDocLine.put("EUITDOCRRN", item1.getEUITDOCRRN());
            euItDocLine.put("DOCLINETYPE", item1.getDOCLINETYPE());
            euItDocLine.put("MATERIALNAME", item1.getMATERIALNAME());
            euItDocLine.put("MATERIALTYPE", item1.getMATERIALTYPE());
            euItDocLine.put("MATERIALDESC", item1.getMATERIALDESC());
            euItDocLine.put("UNITID", item1.getUNITID());
            euItDocLine.put("QTY", item1.getQTY());
            jsonObject1.put("EUITDOCLINE", euItDocLine);
            jsonObject.put("Data", jsonObject1);
            jsonObject.put("MessageName", "EUIT.MLOTAPPLYOUT");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<RDRequisitionBean>>(
                new TypeToken<ResponseBean<RDRequisitionBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<RDRequisitionBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {

                    if (response.body().getBody().getISSCANCODE().equals("N")) {
                        llmlotID.setVisibility(View.VISIBLE);
                        llmEqpID.setVisibility(View.GONE);
                        llmUseID.setVisibility(View.GONE);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mlotID.requestFocus();
                            }
                        }, 500);
                    } else {
                        llmlotID.setVisibility(View.GONE);
                        llmEqpID.setVisibility(View.VISIBLE);
                        llmUseID.setVisibility(View.VISIBLE);
                        adapter.setNewData(response.body().getBody().getMATLIST());
                    }
                }
            }

            @Override
            public void onError(Response<ResponseBean<RDRequisitionBean>> response) {
                super.onError(response);
                loadError(response.getException(), "MLOTAPPLYOUT");
            }
        });


    }

    private void queryXeuitdocList() {
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        try {
            jsonObject1.put("ACTIONTYPE", "ACTIONRDOUTEUITDOCQUERY");
            jsonObject.put("Data", jsonObject1);
            jsonObject.put("MessageName", "EUIT.MLOTAPPLYOUT");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestPostMesForwardUtils(jsonObject, this, new FreeUI_DialogEntityCallBack<ResponseBean<RDRequisitionBean>>(
                new TypeToken<ResponseBean<RDRequisitionBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<ResponseBean<RDRequisitionBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    xeuitdoclist = response.body().getBody().getXEUITDOCLIST();
                    for (RDRequisitionBean.XEUITDOCLISTDTO bean : xeuitdoclist) {
                        String s = bean.getOBJECTRRN() + " | " + bean.getDOCTYPE() + " | " + bean.getDOCUSETO();
                        xeuitdocIDList.add(s);
                        xeuitdocMap.put(s, bean.getOBJECTRRN());
                    }
                }
            }

            @Override
            public void onError(Response<ResponseBean<RDRequisitionBean>> response) {
                super.onError(response);
                loadError(response.getException(), "MLOTAPPLYOUT");
            }
        });
    }


    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        return new FreeUI_AddViewEntity("header", llMain);
    }


}